import React, { useMemo, memo } from 'react';
import { Table, Tag, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';

interface DynamicDataTableProps {
  data: Record<string, any>[];
  loading?: boolean;
  pagination?: any;
  rowKey?: string;
  size?: 'small' | 'middle' | 'large';
}

export const DynamicDataTable: React.FC<DynamicDataTableProps> = memo(({
  data,
  loading = false,
  pagination = { pageSize: 10 },
  rowKey = 'id',
  size = 'middle'
}) => {
  // 动态生成表格列
  const columns: ColumnsType<Record<string, any>> = useMemo(() => {
    if (!data || data.length === 0) return [];

    // 收集所有可能的字段
    const allKeys = new Set<string>();
    data.forEach(item => {
      Object.keys(item).forEach(key => allKeys.add(key));
    });

    // 定义固定列（优先显示）
    const fixedColumns = ['cityName', 'recordedAt', 'statisticDate'];
    const dynamicKeys = Array.from(allKeys).filter(key => 
      !['id', 'cityId', 'createdAt', 'updatedAt', ...fixedColumns].includes(key)
    );

    const cols: ColumnsType<Record<string, any>> = [];

    // 添加固定列
    fixedColumns.forEach(key => {
      if (allKeys.has(key)) {
        const columnConfig = getColumnConfig(key);
        cols.push({
          title: columnConfig.title,
          dataIndex: key,
          key: key,
          width: columnConfig.width,
          render: columnConfig.render,
          fixed: columnConfig.fixed,
        });
      }
    });

    // 添加动态列
    dynamicKeys.forEach(key => {
      const columnConfig = getColumnConfig(key);
      cols.push({
        title: columnConfig.title,
        dataIndex: key,
        key: key,
        width: columnConfig.width,
        render: columnConfig.render,
      });
    });

    return cols;
  }, [data]);

  // 获取列配置
  const getColumnConfig = (key: string) => {
    // 指标配置映射
    const configs: Record<string, any> = {
      cityName: {
        title: '城市',
        width: 100,
        fixed: 'left',
        render: (text: string) => <Tag color="blue">{text}</Tag>
      },
      recordedAt: {
        title: '记录时间',
        width: 160,
        render: (text: string) => new Date(text).toLocaleString('zh-CN')
      },
      statisticDate: {
        title: '统计日期',
        width: 120,
        render: (text: string) => new Date(text).toLocaleDateString('zh-CN')
      },
      temperature: {
        title: '温度(°C)',
        width: 100,
        render: (value: number) => value ? `${value.toFixed(1)}°C` : '-'
      },
      humidity: {
        title: '湿度(%)',
        width: 100,
        render: (value: number) => value ? `${value.toFixed(1)}%` : '-'
      },
      pressure: {
        title: '气压(hPa)',
        width: 110,
        render: (value: number) => value ? `${value.toFixed(1)} hPa` : '-'
      },
      windSpeed: {
        title: '风速(m/s)',
        width: 110,
        render: (value: number) => value ? `${value.toFixed(1)} m/s` : '-'
      },
      windDirection: {
        title: '风向(°)',
        width: 100,
        render: (value: number) => value ? `${value.toFixed(0)}°` : '-'
      },
      visibility: {
        title: '能见度(km)',
        width: 110,
        render: (value: number) => value ? `${value.toFixed(1)} km` : '-'
      },
      uvIndex: {
        title: 'UV指数',
        width: 90,
        render: (value: number) => value ? value.toFixed(1) : '-'
      },
      weatherCondition: {
        title: '天气状况',
        width: 100,
        render: (text: string) => text ? <Tag color="green">{text}</Tag> : '-'
      },
      dataPointCount: {
        title: '数据点数',
        width: 90,
        render: (value: number) => <Tag color="orange">{value}</Tag>
      }
    };

    // 处理动态统计字段 (如 temperature_avg, humidity_max)
    if (key.includes('_')) {
      const parts = key.split('_');
      const metricKey = parts.slice(0, -1).join('_');
      const aggType = parts[parts.length - 1];
      
      const metricNames: Record<string, string> = {
        temperature: '温度',
        humidity: '湿度', 
        pressure: '气压',
        windSpeed: '风速',
        windDirection: '风向',
        visibility: '能见度',
        uvIndex: 'UV指数',
        weatherCondition: '天气'
      };
      
      const aggNames: Record<string, string> = {
        avg: '平均',
        max: '最高',
        min: '最低',
        dominant: '主要'
      };
      
      const metricName = metricNames[metricKey] || metricKey;
      const aggName = aggNames[aggType] || aggType;
      
      return {
        title: (
          <Tooltip title={`${metricName}的${aggName}值`}>
            {`${metricName}(${aggName})`}
          </Tooltip>
        ),
        width: 120,
        render: (value: any) => {
          if (value === null || value === undefined) return '-';
          
          if (typeof value === 'number') {
            const unit = metricKey === 'temperature' ? '°C' : 
                        metricKey === 'humidity' ? '%' : 
                        metricKey === 'pressure' ? ' hPa' :
                        metricKey === 'windSpeed' ? ' m/s' :
                        metricKey === 'windDirection' ? '°' :
                        metricKey === 'visibility' ? ' km' : '';
            return `${value.toFixed(1)}${unit}`;
          }
          
          return aggType === 'dominant' ? <Tag color="blue">{value}</Tag> : value.toString();
        }
      };
    }

    // 默认配置
    return configs[key] || {
      title: key,
      width: 120,
      render: (value: any) => {
        if (value === null || value === undefined) return '-';
        if (typeof value === 'number') return value.toFixed(2);
        if (typeof value === 'boolean') return value ? '是' : '否';
        return value.toString();
      }
    };
  };

  // 移除compact逻辑，统一使用相同的表格结构

  return (
    <div>
      <Table
        dataSource={data}
        columns={columns}
        rowKey={rowKey}
        loading={loading}
        pagination={pagination}
        size={size}
        scroll={{ x: 'max-content' }}
        bordered
        summary={(pageData) => {
          if (!pageData || pageData.length === 0) return null;
          
          return (
            <Table.Summary>
              <Table.Summary.Row>
                <Table.Summary.Cell index={0}>
                  <Tag color="purple">统计汇总</Tag>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={1}>
                  {pageData.length} 条记录
                </Table.Summary.Cell>
                {/* 可以添加更多汇总信息 */}
              </Table.Summary.Row>
            </Table.Summary>
          );
        }}
      />
    </div>
  );
});

export default DynamicDataTable;